package org.charry.lib.commons.mail;

import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.mail.*;
import org.charry.lib.commons.log.StackUtility;


/**
 * Email service wrapper class.
 * 
 * @author wcharry
 * 
 */
public final class EMailService {
	private static Log log = LogFactory.getLog(EMailService.class);
	private String emailServer = "exchange.charry.org";
	private String fromAddress = "noreply@charry.org";

	/**
	 * Return the email server hostname.
	 * 
	 * @return server name
	 */
	public String getEmailServer() {
		return emailServer;
	}

	/**
	 * Set email server hostname.
	 * 
	 * @param emailServer
	 *            email server name
	 */
	public void setEmailServer(final String emailServer) {
		this.emailServer = emailServer;
	}

	public String getFromAddress() {
		return fromAddress;
	}

	public void setFromAddress(String fromAddress) {
		this.fromAddress = fromAddress;
	}

	public boolean sendMail(String subject, String body, String to) {
		return sendMail(subject, body, to, null);
	}

	public boolean sendMail(String subject, String body, String to, String cc) {
		return sendMail(subject, body, to, null, null);
	}

	/**
	 * Function to send an email.
	 * 
	 * @param subject
	 *            email subject
	 * @param body
	 *            email body
	 * @param to
	 *            to list
	 * @param cc
	 *            cc list
	 * @param bcc
	 *            bcc list
	 * @return if sending is successful
	 */
	public boolean sendMail(final String subject, final String body,
			final String to, final String cc, final String bcc) {
		boolean bSuccess = true;
		HtmlEmail email = new HtmlEmail();

		try {
			email.setHostName(emailServer);
			email.setFrom(fromAddress);
			email.setSubject(subject);
			StringTokenizer stTo = new StringTokenizer(to, ";");
			while (stTo.hasMoreTokens()) {
				email.addTo(stTo.nextToken());
			}

			if (cc != null && !cc.equals("")) {
				StringTokenizer stCc = new StringTokenizer(to, ";");
				while (stCc.hasMoreTokens()) {
					email.addCc(stCc.nextToken());
				}
			}

			if (bcc != null && !bcc.equals("")) {
				StringTokenizer stBcc = new StringTokenizer(to, ";");
				while (stBcc.hasMoreTokens()) {
					email.addBcc(stBcc.nextToken());
				}
			}

			email.setHtmlMsg(body);
			log.info("Send mail, subject:" + subject + ", To:" + to);
			email.send();
		} catch (EmailException e) {
			log.error("EmailException:" + e);
			bSuccess = false;
		} catch (Exception e) {
			StackUtility.logStackTrace(log, e);
			bSuccess = false;
		}

		return bSuccess;
	}
}
